package com.sc.server.system.common.config.mybatisPls;
import com.sc.server.system.common.utils.UserUtils;
import net.sf.jsqlparser.expression.StringValue;
import net.sf.jsqlparser.schema.Column;
import com.baomidou.mybatisplus.plugins.parser.tenant.TenantHandler;
import net.sf.jsqlparser.expression.operators.relational.InExpression;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.operators.relational.ExpressionList;

import java.util.ArrayList;
import java.util.List;

public class MyTentantHandler implements TenantHandler {
    @Override
    public Expression getTenantId() {
        final boolean multipleTenantIds = true;
        if (multipleTenantIds) {
            return multipleTenantIdCondition();
        } else {
            return singleTenantIdCondition();
        }
    }

    private Expression singleTenantIdCondition() {
        return new StringValue(UserUtils.getTenantId());//ID自己想办法获取到
    }

    private Expression multipleTenantIdCondition() {
        final InExpression inExpression = new InExpression();
        inExpression.setLeftExpression(new Column(getTenantIdColumn()));
        final ExpressionList itemsList = new ExpressionList();
        final List<Expression> inValues = new ArrayList<>(2);
        if(UserUtils.getTenantId().equals("0")){
            return null;
        }
        inValues.add(new StringValue(UserUtils.getTenantId()));//ID自己想办法获取到
        inValues.add(new StringValue("0"));
        itemsList.setExpressions(inValues);
        inExpression.setRightItemsList(itemsList);
        return inExpression;
    }

    @Override
    public String getTenantIdColumn() {
        return "tenant_id";
    }

    @Override
    public boolean doTableFilter(String tableName) {
        // 这里可以判断是否过滤表
                /*if ("user".equals(tableName)) {
                    return true;
                }*/
//                return false;
        return false;
    }
}
